package com.ttxs.fileformathandling.service.impl;
import java.util.Date;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ttxs.apicommon.model.entity.User;
import com.ttxs.fileformathandling.common.ErrorCode;
import com.ttxs.fileformathandling.constant.CommonConstant;
import com.ttxs.fileformathandling.exception.BusinessException;


import com.ttxs.fileformathandling.model.dto.user.UserQueryRequest;



import com.ttxs.fileformathandling.model.enums.UserRoleEnum;
import com.ttxs.fileformathandling.model.vo.LoginUserVO;
import com.ttxs.fileformathandling.model.vo.UserVO;


import com.ttxs.fileformathandling.service.UserService;
import com.ttxs.fileformathandling.mapper.UserMapper;


import com.ttxs.fileformathandling.utils.SqlUtils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import org.springframework.stereotype.Service;

import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;

import java.util.*;

/**
 * @author cwt
 * @description 针对表【user(用户表)】的数据库操作Service实现
 * @createDate 2023-05-21 02:21:09
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    private static final String SALT = "ttxs";

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword, String email) {
        //1.校验空值
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, email)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数不能为空");
        }
        //2.用户账户名长度不得小于5位
        if (userAccount.length() < 5) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号不能少于5位");
        }
        //3.用户密码长度不少于8位
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码不能少于8位");
        }
        //4.第二次输入密码与第一次密码相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "前后两次输入的密码不一致");
        }
        //todo 5. 正则匹配复杂密码
        //todo 6. 邮箱合法性验证
        //7.账户不能重复
        synchronized (userAccount.intern()) {   //保证唯一
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("userAccount", userAccount);
            //查询账号
            Long count = this.baseMapper.selectCount(userQueryWrapper);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "该账号已被注册");
            }
            //加密
            String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
            //分配 accessKey  secretKey
            String accessKey = DigestUtil.md5Hex(SALT + userAccount + RandomUtil.randomNumbers(5));
            String secretKey = DigestUtil.md5Hex(SALT + userAccount + RandomUtil.randomNumbers(6));
            //插入数据
            User user = new User();

            user.setUserAccount(userAccount);
            user.setUserName(userAccount);  //用户名默认与账号相同
            user.setUserPassword(encryptPassword);
            user.setAccessKey(accessKey);
            user.setSecretKey(secretKey);
            user.setEmail(email);
            boolean result = this.save(user); //插入数据
            if (!result) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库异常");
            }
            return user.getId();    //返回用户id
        }
    }

    @Override
    public LoginUserVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //1.校验空值
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数不能为空");
        }
        //2.账号长度不少于5位
        if (userAccount.length() < 5) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号长度不能少于5位");
        }
        //3.用户密码长度不低于8位
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度不能少于8位");
        }
        //4.密码加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        //5.查询用户是否存在
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("userAccount", userAccount);
        userQueryWrapper.eq("userPassword", encryptPassword);
        User user = this.baseMapper.selectOne(userQueryWrapper);
        //没有查询到匹配的记录
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        //6.记录用户登录态
        request.getSession().setAttribute("USER_LOGIN_STATE", user);
        //7.返回用户脱敏信息
        return this.getLoginUserVO(user);
    }


    @Override
    public User getLoginUser(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute("USER_LOGIN_STATE");
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        //如果存在，从数据库中获最新用户数据（追求性能的话注释，走缓存）
        Long userId = currentUser.getId();
        currentUser = this.getById(userId);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }

    @Override
    public User getLoginUserPermitNull(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute("USER_LOGIN_STATE");
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            return null;
        }
        return this.getById(currentUser.getId());
    }

    @Override
    public boolean notAdmin(User user) {
        return user == null || !UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }

    @Override
    public boolean notAdmin(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute("USER_LOGIN_STATE");
        User user = (User) userObj;
        return notAdmin(user);
    }

    @Override
    public boolean userLogout(HttpServletRequest request) {
        if (request.getSession().getAttribute("USER_LOGIN_STATE") == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "用户并未登录");
        }
        //清除登录态
        request.getSession().removeAttribute("USER_LOGIN_STATE");
        return true;
    }

    @Override
    public LoginUserVO getLoginUserVO(User user) {
        //只处理数据，不处理业务
        if (user == null) {
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtils.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (userList == null || userList.size() == 0) {
            return new ArrayList<>();
        }
        List<UserVO> userVOList = new ArrayList<>(userList.size());
        for (User user : userList) {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            userVOList.add(userVO);
        }
        //一次性搞定
        //return userList.stream().map(this::getUserVO).collect(Collectors.toList());
        return userVOList;
    }

    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(id != null, "id", id);
        queryWrapper.eq(StringUtils.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(StringUtils.isNotBlank(userName), "userName", userName);
        queryWrapper.like(StringUtils.isNotBlank(userProfile), "userProfile", userProfile);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        return queryWrapper;
    }
}




